package com.tusuo.stds.ui.lab;

import android.content.Context;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.biz.CurrentUser;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.rest.UserInfo;
import com.tusuo.stds.util.Utils;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.1
 *
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(LabPresenter.class)
class LabPresenter extends MvpBasePresenter<LabView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<ApiResult> mSetOpenSimilaritySubscriber = null;

    LabPresenter(Context context) {
        mContext = context;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initLabPresenterComponent().inject(this);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mSetOpenSimilaritySubscriber != null) {
            mSetOpenSimilaritySubscriber.unsubscribe();
            mSetOpenSimilaritySubscriber = null;
        }
        super.detachView(retainInstance);
    }

    void setOpenSimilarity(boolean isOpening) {
        mSetOpenSimilaritySubscriber = new SetOpenSimilaritySubscriber();
        mApiHelper.setOpenSimilarity(mSetOpenSimilaritySubscriber, isOpening);
    }

    void getUserSimilarityState() {
        mApiHelper.getUserInfo(new GetUserInfoSubscriber());
    }

    private class SetOpenSimilaritySubscriber extends Subscriber<ApiResult> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final ApiResult result) {
            if (result.checkState(mContext)) {
            }
        }
    }

    private class GetUserInfoSubscriber extends Subscriber<UserInfo> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final UserInfo userInfo) {
            if (userInfo.checkState(mContext) && getView() != null) {
                getView().setSimilarityState(userInfo.IsOpenSimilarity);
            }
        }
    }
}
